import router from "@/router/index.ts";
import { addUserRouter } from "@/router/helper.ts";

router.beforeEach(async (to) => {
  const KEY = "userStore";
  const userData: string | null = window.sessionStorage.getItem(KEY) || "";
  const isAuthed: boolean = !!userData;

  if (to.path !== "/login") {
    if (isAuthed) {
      if (!to.matched.length) {
        const userMenu = JSON.parse(userData)?.userData?.sysMenus || [];
        await addUserRouter(userMenu);
        return to.fullPath;
      } else {
        return true;
      }
    } else {
      return "/login";
    }
  } else {
    return true;
  }
});
